package com.pdd.autoconf.scope;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.Scope;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author:liyangpeng
 * @date:2020/8/28 16:30
 */
public class PddScope implements Scope, BeanFactoryPostProcessor {

    public static final String scopeName="pddScope";

    private Map<String,Object> beans=new ConcurrentHashMap<>(16);

    @Override
    public Object get(String name, ObjectFactory<?> objectFactory) {
        Object bean = beans.get(name);
        if(bean==null){
            bean = objectFactory.getObject();
            beans.put(name,bean);
        }
        return bean;
    }

    @Override
    public Object remove(String name) {
        return beans.remove(name);
    }

    public void refreshAll(){
        this.beans.clear();
    }

    @Override
    public void registerDestructionCallback(String name, Runnable callback) {

    }

    @Override
    public Object resolveContextualObject(String key) {
        return null;
    }

    @Override
    public String getConversationId() {
        return null;
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        beanFactory.registerScope(PddScope.scopeName,this);
    }
}
